package com.fept.msgcore.msgserver.netty.handler;

import com.fept.msgcore.msgserver.protocol.frame.Frame;
import com.fept.msgcore.msgserver.protocol.frame.ProtocolMessage;
import com.fept.msgcore.msgserver.util.system.ByteUtil;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.InetAddress;
import java.net.InetSocketAddress;

/**
 * Created by Srma on 1/13/2017.
 */
public class ProtocolMessageEncoder extends MessageToByteEncoder<Frame> {

    private static Logger logger = LoggerFactory.getLogger(ProtocolMessageEncoder.class);
    public String name;

    public ProtocolMessageEncoder(String name) {
        this.name = name;
    }


    @Override
    protected void encode(ChannelHandlerContext ctx, Frame frame, ByteBuf bf) throws Exception
    {
        try {
            InetAddress hostIPAddress = ((InetSocketAddress) ctx.channel()
                    .remoteAddress()).getAddress();
            String hostIP = hostIPAddress.getHostAddress();
            int hostPort = ((InetSocketAddress) ctx.channel().remoteAddress())
                    .getPort();

            /**
             * 设置目标ip和端口
             */
            frame.setIp(hostIP);
            frame.setPort(hostPort);

            /**
             * packing frame
             */
            byte[] buf = ProtocolMessage.packing(frame);
            bf.writeBytes(buf);

            /**
             * log readable frame
             */
            logger.info(String.format("[to: %s %d]: %s", hostIP,
                    hostPort, frame.toString()));

            /**
             * log raw message
             */
            logger.info(String.format("[to: %s %d]: %s", hostIP,
                    hostPort, ByteUtil.dumpMessage(buf)));
        } catch (Exception e) {
            logger.error(String.format(
                    "exception on encoding client messages: %s", e));
            logger.error(e.getMessage());
        }
    }



}
